import { Dialog, Grid, Toast } from "antd-mobile";

/**
 * Components
 */
import Canvas from "@/components/canvas";
import Tabs from "@/components/tabs";
/**
 * Resources
 */
import iconDelete from "@/assets/icon_delete.png";
import iconShare from "@/assets/icon_share.png";
import { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useSetState } from "ahooks";

/**
 * Types
 */
type State = {
  list: {
    colors: string[];
    id: string;
    name: string;
    time: number;
  }[];
  selected: boolean;
  selectedKeys: number[];
};

const PageIndex: React.FC = () => {
  /**
   * Hooks
   */
  const navigate = useNavigate();

  /**
   * States
   */
  const [state, setState] = useSetState<State>({
    list: [],
    selected: false,
    selectedKeys: [],
  });

  /**
   * Effects
   */
  useEffect(() => {
    if (!JeeWeb) return;

    JeeWeb.get("index", ({ result = [] }) => {
      setState({
        list: result || [],
      });
    });

    // 有分享信息
    if (JeeWeb.shareInfo) {
      const share = JeeWeb.shareInfo;

      // 获取当前用户
      JeeWeb.getUserProfile((user) => {
        // 如果是自己分享的，不处理
        if (share.id === user.result.id) {
          return;
        }

        // 获取分享列表
        JeeWeb.get("share", ({ result = [] }) => {
          const list = result || [];

          // 是否已经收藏
          if (
            list.some(
              (item: any) => item.id === share.id && item.time === share.time
            )
          ) {
            return;
          }

          navigate("/preview", {
            state: share,
          });
        });
      });
    }
  }, []);

  return (
    <div className="jj-page">
      <header className="jj-header">
        <Tabs activeKey="/" />

        <div
          className="jj-btn"
          onClick={() => {
            setState({ selected: !state.selected, selectedKeys: [] });
          }}
        >
          {state.selected ? "取消" : "选择"}
        </div>
      </header>

      <main className="jj-main">
        <Grid columns={2} gap={11}>
          {state.list.map((item, index) => (
            <Grid.Item
              key={index}
              style={{ textAlign: "center" }}
              onClick={() => {
                if (!state.selected) {
                  return JeeWeb.set("current", { index, item }, () => {
                    navigate("/create");
                  });
                }

                if (state.selectedKeys.includes(index)) {
                  setState({
                    selectedKeys: state.selectedKeys.filter(
                      (key) => key !== index
                    ),
                  });
                } else {
                  setState({
                    selectedKeys: [...state.selectedKeys, index],
                  });
                }
              }}
            >
              <div className="jj-item">
                {state.selected && (
                  <div
                    className={`jj-item-selected ${state.selectedKeys.includes(index) ? "jj-item-selected-active" : ""}`}
                  />
                )}

                <div className="jj-item-wrap">
                  <Canvas colors={item.colors} />
                </div>
              </div>
            </Grid.Item>
          ))}
        </Grid>

        {state.list.length === 0 && (
          <div
            style={{
              display: "flex",
              justifyContent: "center",
              alignItems: "center",
              height: "100%",
              color: "#7a8799",
              fontSize: "15px",
            }}
          >
            - 暂无数据 -
          </div>
        )}
      </main>

      <footer
        className={`jj-footer ${state.selected ? "jj-footer-border" : ""}`}
      >
        {state.selected ? (
          <Grid columns={2} gap={100}>
            <Grid.Item
              style={{ textAlign: "center" }}
              onClick={() => {
                if (state.selectedKeys.length === 0) {
                  return Toast.show("请选择项目");
                }

                if (state.selectedKeys.length > 1) {
                  return Toast.show("只能分享 1 个项目");
                }

                JeeWeb.share({
                  shareInfo: state.list[state.selectedKeys[0]],
                  callback: ({ code }) => {
                    Toast.show({
                      content: "分享成功",
                    });

                    if (code === 200) {
                      setState({
                        selected: false,
                        selectedKeys: [],
                      });
                    }
                  },
                });
              }}
            >
              <img
                alt=""
                src={iconShare}
                style={{ width: "54px", height: "54px", verticalAlign: "top" }}
              />

              <div
                style={{
                  marginTop: "6px",
                  color: "#2E2F33",
                  fontSize: "12px",
                  lineHeight: "14px",
                }}
              >
                分享项目
              </div>
            </Grid.Item>

            <Grid.Item
              style={{ textAlign: "center" }}
              onClick={() => {
                if (state.selectedKeys.length === 0) {
                  return Toast.show("请选择项目");
                }

                Dialog.confirm({
                  title: "删除项目",
                  content: "确认是否删除涂鸦作品",
                  onConfirm: () => {
                    const list = state.list.filter(
                      (_, index) => !state.selectedKeys.includes(index)
                    );

                    JeeWeb &&
                      JeeWeb.set("index", list, () => {
                        setState({
                          list,
                          selected: false,
                          selectedKeys: [],
                        });

                        Toast.show({
                          content: "删除成功",
                        });
                      });
                  },
                });
              }}
            >
              <img
                alt=""
                src={iconDelete}
                style={{ width: "54px", height: "54px", verticalAlign: "top" }}
              />

              <div
                style={{
                  marginTop: "6px",
                  color: "#2E2F33",
                  fontSize: "12px",
                  lineHeight: "14px",
                }}
              >
                删除项目
              </div>
            </Grid.Item>
          </Grid>
        ) : (
          <div
            className="jj-create"
            onClick={() => {
              JeeWeb &&
                JeeWeb.remove("current", () => {
                  navigate("/create");
                });

              !JeeWeb && navigate("/create");
            }}
          />
        )}
      </footer>
    </div>
  );
};

export default PageIndex;
